// 全局配置
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus, {ElMessage} from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import axios from "axios";
import axiosRetry from "axios-retry";
const client = axios.create();
axiosRetry(client, { retries: 3 })

// 配置后端服务器根路径
const BASE_URL = 'http://localhost:8080';
// 配置给windows对象，该属性为全局属性
window.BASE_URL = BASE_URL;

const app = createApp(App)

// 给app(vue对象)添加一个属性，该属性为全局属性
app.config.globalProperties.BASE_URL = BASE_URL;

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

app.use(ElementPlus,{ locale: zhCn }).use(store).use(router).mount('#app')

// 解决ResizeObserver Error
const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    }
}
const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16);
        super(callback);
    }
}

// 定义全局方法,获取当前登录的用户数据
window.getUser = ()=>{
    return localStorage.user ? JSON.parse(localStorage.user) : null;
}

// 配置路由守卫
router.beforeEach((to, from, next) => {
    let user = localStorage.user;
    if (to.path !==  '/login' && !user){
        next('/login');
        ElMessage.error('请先登录');
    }else {
        next();
    }
})

// 获取字典选项
window.loadDictOptions = (object,dictCode)=>{
    client.get(BASE_URL+'/v1/dictOption/select/'+dictCode)
        .then((response)=>{
            if (response.data.code == 2000){
                object.value = response.data.data;
            } else {
                Element.error(response.data.msg);
            }
        })
}